<?php

namespace app\api\controller;
use app\common\logic\CartLogic;
use app\common\logic\GoodsActivityLogic;
use app\common\logic\CouponLogic;
use app\common\logic\OrderLogic;
use app\common\model\Goods;
use app\common\model\SpecGoodsPrice;
use app\common\logic\IntegralLogic;
use think\Db;
use think\Url;
use think\Request;
use think\Validate;
use think\Session;
class Cart extends ApiCommon{

    public $cartLogic; // 购物车逻辑操作类    
    public $user_id = 0;
    public $user = array();
    /**
     * 析构流函数
     */
    public function  __construct() {
    	
		$this->nocheckArr = ['regionlist'];
        parent::__construct();
//      $this->cartLogic = new CartLogic();
//      if (session('?user')) {
//          $user = session('user');
//          $user = M('users')->where("user_id", $user['user_id'])->find();
//          session('user', $user);  //覆盖session 中的 user
//          $this->user = $user;
//          $this->user_id = $user['user_id'];
//          $this->assign('user', $user); //存储用户信息
//          // 给用户计算会员价 登录前后不一样
//          if ($user) {
//              $user['discount'] = (empty($user['discount'])) ? 1 : $user['discount'];
//              if ($user['discount'] != 1) {
//                  $c = Db::name('cart')->where(['user_id' => $user['user_id'], 'prom_type' => 0])->where('member_goods_price = goods_price')->count();
//                  $c && Db::name('cart')->where(['user_id' => $user['user_id'], 'prom_type' => 0])->update(['member_goods_price' => ['exp', 'goods_price*' . $user['discount']]]);
//              }
//          }
//      }
    }

    public function index(){
    	$uid = I('uid/d',0);
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($uid);
        $cartList = $cartLogic->getCartList();//用户购物车
        $userCartGoodsTypeNum = $cartLogic->getUserCartGoodsTypeNum();//获取用户购物车商品总数
		//return ;
		exit(json_encode(['status'=>'ok','arr'=>$cartList,'userCartGoodsTypeNum'=>$userCartGoodsTypeNum]));
    }
	
	/**
     * ajax 将商品加入购物车
     */
    function AddCart()
    {
        $goods_id = I("goods_id/d"); // 商品id
        $goods_num = I("goods_num/d");// 商品数量
        $item_id = I("item_id/d"); // 商品规格id
        $user_id = I("uid/d",0);
		
		$this->user_id = $user_id;
        if(empty($goods_id)){
            $this->ajaxReturn(['status'=>-1,'msg'=>'请选择要购买的商品','result'=>'']);
        }
        if(empty($goods_num)){
            $this->ajaxReturn(['status'=>-1,'msg'=>'购买商品数量不能为0','result'=>'']);
        }
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        $cartLogic->setGoodsModel($goods_id);
        if($item_id){
            $cartLogic->setSpecGoodsPriceModel($item_id);
        }
        $cartLogic->setGoodsBuyNum($goods_num);
        $result = $cartLogic->addGoodsToCart();
        exit(json_encode($result));
    }
	
	/**
     *  购物车加减
     */
    public function changeNum(){

		$ids = input('id/d', 0);
		$goods_num = input('goods_num/d', 0);
        if (empty($ids) ||$ids == 0) {
			$this->returnMsg(-100,'请选择要更改的商品');
        }
        $cartLogic = new CartLogic();
        $result = $cartLogic->changeNum($ids,$goods_num);
        
		if($result['status'] == 1){
			$result['status']='ok';
		}
        return json_encode($result);
    }

    /**
     * 更新购物车，并返回计算结果
     */
    public function AsyncUpdateCart()
    {
        $cart = input('cart/a', []);
		$this->user_id = input('uid/d',0);
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        $result = $cartLogic->AsyncUpdateCart($cart);
//      $this->ajaxReturn($result);
		return json_encode($result);
    }

    

    /**
     * 删除购物车商品
     */
    public function delete(){
        $cart_ids = input('cart_ids/s','');
		$user_ids = input('uid/d',0);
		
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($user_ids);
        $result = $cartLogic->delete($cart_ids);
        if($result !== false){
            return json_encode(['status'=>'ok','msg'=>'删除成功','result'=>$result]);
        }else{
            return json_encode(['status'=>'ok','msg'=>'删除失败','result'=>$result]);
        }
    }

    /**
     * 购物车第二步确定页面（在API里面只需要获得优惠券和地址信息即可）
     */
    public function cart2(){
        $goods_id = input("goods_id/d"); // 商品id
        $goods_num = input("goods_num/d");// 商品数量
        $item_id = input("item_id/d"); // 商品规格id
        $action = input("action"); // 行为
        $user_id = input('uid/d',0);
		
		//如果没有userid 先登陆
        if ($user_id == 0){
            $this->returnMsg(-1000,'未登陆');
        }
		
		$this->user_id = $user_id;
		
		//获得玩家对应地址
		$address = M('user_address')->where(['user_id'=>$this->user_id])->find();
        

        $cartLogic = new CartLogic();
        $couponLogic = new CouponLogic();
        $cartLogic->setUserId($this->user_id);
        //立即购买
        if($action == 'buy_now'){
            if(empty($goods_id)){
//              $this->error('请选择要购买的商品');
				$this->returnMsg(-2,'请选择要购买的商品');
            }
            if(empty($goods_num)){
//              $this->error('购买商品数量不能为0');
				$this->returnMsg(-3,'购买商品数量不能为0');
            }
            $cartLogic->setGoodsModel($goods_id);
            if($item_id){
                $cartLogic->setSpecGoodsPriceModel($item_id);
            }
            $cartLogic->setGoodsBuyNum($goods_num);
            $result = $cartLogic->buyNow();
            if($result['status'] != 1){
//              $this->error($result['msg']);
				$this->returnMsg(-4,$result['msg']);
            }
            $cartList['cartList'][0] = $result['result']['buy_goods'];
            $cartGoodsTotalNum = $goods_num;
        }else{
            if ($cartLogic->getUserCartOrderCount() == 0){
				$this->returnMsg(-1,'你的购物车没有选中商品');
            }
            $cartList['cartList'] = $cartLogic->getCartList(1); // 获取用户选中的购物车商品
        }

        $cartGoodsList = get_arr_column($cartList,'goods');
        $cartGoodsId = get_arr_column($cartGoodsList,'goods_id');
        $cartGoodsCatId = get_arr_column($cartGoodsList,'cat_id');
        $cartPriceInfo = $cartLogic->getCartPriceInfo($cartList['cartList']);  //初始化数据。商品总额/节约金额/商品总共数量
        $userCouponList = $couponLogic->getUserAbleCouponList($this->user_id, $cartGoodsId, $cartGoodsCatId);//用户可用的优惠券列表
        $cartList = array_merge($cartList,$cartPriceInfo);
        $userCartCouponList = $cartLogic->getCouponCartList($cartList, $userCouponList);
        $shippingList = M('Plugin')->where("`type` = 'shipping' and status = 1")->cache(true,TPSHOP_CACHE_TIME)->field('code,name,version,type,icon,scene')->select();// 物流公司
        $userextend = M('user_extend')->where("user_id=$user_id")->select();
		
		$extendstr = '';
		if(count($userextend)>0){
			//抬头:税号:姓名
			$invoice_titles = $userextend[0]['invoice_title'];
			$extendstr = $invoice_titles.":".$userextend[0]['taxpayer'].":".$userextend[0]['realname'];
		}
		
        $backArr = [];
		$backArr['userCartCouponList'] = $userCartCouponList;	//优惠券，用able判断是否可用
		$backArr['cartGoodsTotalNum'] = $cartGoodsTotalNum;		//商品总数量
		$backArr['cartPriceInfo'] = $cartPriceInfo;				//计算后的商品总价
        $backArr['address'] = $address;
        $backArr['cartList'] = $cartList['cartList'];
		$backArr['extend'] = $extendstr;
		$backArr['shippingList'] = $shippingList;// 物流公司
        $this->returnMsg('ok','',$backArr);
    }

    /**
     * ajax 获取订单商品价格 或者提交 订单
     */
    public function cart3(){

        
        $address_id = I("address_id/d"); //  收货地址id
        $shipping_code =  I("shipping_code/s",''); //  物流编号
        $invoice_title = I('invoice_title'); // 发票
        $coupon_id =  I("coupon_id/d"); //  优惠券id
        $pay_points =  I("pay_points/d",0); //  使用积分
        $user_money =  I("user_money/f",0); //  使用余额
        $user_note = trim(I('user_note'));   //买家留言
        $goods_id = input("goods_id/d"); // 商品id
        $goods_num = input("goods_num/d");// 商品数量
        $item_id = input("item_id/d"); // 商品规格id
        $action = input("action"); // 立即购买
        $paypwd =  I("paypwd",''); // 支付密码
		$user_id = input('uid/d',0);
		$act = input('act/s','');
		
		$this->user_id = $user_id;
		if($this->user_id <= 0){
            $this->returnMsg('-5','登录超时请重新登录');
        }
		
		if(!$address_id) 
			$this->returnMsg('-4','请先填写收货人信息');
		
        $user_money = $user_money ? $user_money : 0;
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        if($action == 'buy_now'){
        	//立即购买状态
            $cartLogic->setGoodsModel($goods_id);
            if($item_id){
                $cartLogic->setSpecGoodsPriceModel($item_id);
            }
            $cartLogic->setGoodsBuyNum($goods_num);
            $result = $cartLogic->buyNow();
            if($result['status'] != 1){
//              $this->ajaxReturn($result);
				$this->returnMsg($result['status'],$result['msg']);
            }
            $order_goods[0] = $result['result']['buy_goods'];
        }else{
            $userCartList = $cartLogic->getCartList(1);
            if($userCartList){
                $order_goods = collection($userCartList)->toArray();
            }else{
				$this->returnMsg('-1','你的购物车没有选中商品');
            }
            foreach ($userCartList as $cartKey => $cartVal) {
                if($cartVal->goods_num > $cartVal->limit_num){
					$this->returnMsg('-2',$cartVal->goods_name.'购买数量不能大于'.$cartVal->limit_num,['limit_num'=>$cartVal->limit_num]);
                }
            }
        }
        $address = M('UserAddress')->where("address_id", $address_id)->find();
        $result = calculate_price($this->user_id,$order_goods,$shipping_code,0,$address['province'],$address['city'],$address['district'],$pay_points,$user_money,$coupon_id);
        
        if($result['status'] < 0)
            $this->returnMsg('-3','没有找到地址对应的商品价格');
		
        // 订单满额优惠活动
        $order_prom = get_order_promotion($result['result']['order_amount']);
        $result['result']['order_amount'] = $order_prom['order_amount'] ;
        $result['result']['order_prom_id'] = $order_prom['order_prom_id'] ;
        $result['result']['order_prom_amount'] = $order_prom['order_prom_amount'] ;

        $car_price = array(
            'postFee'      => $result['result']['shipping_price'], // 物流费
            'couponFee'    => $result['result']['coupon_price'], // 优惠券
            'balance'      => $result['result']['user_money'], // 使用用户余额
            'pointsFee'    => $result['result']['integral_money'], // 积分支付
            'payables'     => $result['result']['order_amount'], // 应付金额
            'goodsFee'     => $result['result']['goods_price'],// 商品价格
            'order_prom_id' => $result['result']['order_prom_id'], // 订单优惠活动id
            'order_prom_amount' => $result['result']['order_prom_amount'], // 订单优惠活动优惠了多少钱
        );
		
		// 提交订单
        if($act == 'submit_order') {
            $pay_name = '';
            if(empty($coupon_id) && !empty($couponCode)){
                $coupon_id = M('CouponList')->where("code", $couponCode)->getField('id');
            }
			
			//1.首先拿到地址id
			$city = $address['city'];
			$province = $address['province'];
			//2.拿到物流id
			//3.查看物流是否到这个地址
//			shipping_area_id

			if($city && $city>0){
				$province = $city;
			}
			
			$areares = Db::query("select * from tp_area_region where shipping_area_id in 
			(select shipping_area_id from tp_shipping_area where shipping_code = '$shipping_code') 
			and region_id = $province");
			
			if(count($areares)<=0){
				$this->returnMsg('-1','该快递不能到达此目的地，请选择其他快递');
			}
			
            $orderLogic = new OrderLogic();
            $orderLogic->setAction($action);
            $orderLogic->setCartList($order_goods);
            $result = $orderLogic->addOrder($this->user_id,$address_id,$shipping_code,$invoice_title,$coupon_id,$car_price,$user_note,$pay_name); // 添加订单
            
            if($result['status']==1){
            	$order = M('Order')->where(['order_id'=>$result['result']])->find();
				$this->returnMsg('ok','提交订单成功',$order);
            }
			else{
				exit(json_encode($result));
			}
            
        }
		
        $this->returnMsg('ok','计算成功',$car_price);
    }

	//获得配送地址列表
	public function regionlist(){
		$regionList = get_region_list_api();
		$this->returnMsg('ok','',$regionList);
	}
	
	//获取对应国家下面的省
	public function getRegionByParentId()
    {
        $parent_id = input('parent_id');
        if($parent_id){
            $region_list = Db::name('region')->field('id,name')->where(['parent_id'=>$parent_id])->select();
			$this->returnMsg('ok','获取成功',$region_list);
        }
        $this->returnMsg('0','获取失败，参数错误',[]);
    }
	
    /*
     * 订单支付页面
     */
    public function cart4(){

        $order_id = I('order_id/d');
		$user_id = I('uid/d');
		$this->user_id = $user_id;
		
        $order_where = ['user_id'=>$this->user_id,'order_id'=>$order_id];
        $order = M('Order')->where($order_where)->find();
        if($order['order_status'] == 3){
//          $this->error('该订单已取消',U("Mobile/Order/order_detail",array('id'=>$order_id)));
			$this->returnMsg('-1','订单已经取消',array('id'=>$order_id));
        }
        if(empty($order) || empty($this->user_id)){
            $this->returnMsg('-2','订单不存在');
        }
        // 如果已经支付过的订单直接到订单详情页面. 不再进入支付页面
        if($order['pay_status'] == 1){
             $this->returnMsg('-3','订单已经支付过');
        }
        $orderGoodsPromType = M('order_goods')->where(['order_id'=>$order['order_id']])->getField('prom_type',true);
        $payment_where['type'] = 'payment';
        $no_cod_order_prom_type = ['4,5'];//预售订单，虚拟订单不支持货到付款
        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            //微信浏览器
            if(in_array($order['order_prom_type'],$no_cod_order_prom_type) || in_array(1,$orderGoodsPromType)){
                //预售订单和抢购不支持货到付款
                $payment_where['code'] = 'weixin';
            }else{
                $payment_where['code'] = array('in',array('weixin','cod'));
            }
        }else{
            if(in_array($order['order_prom_type'],$no_cod_order_prom_type) || in_array(1,$orderGoodsPromType)){
                //预售订单和抢购不支持货到付款
                $payment_where['code'] = array('neq','cod');
            }
            $payment_where['scene'] = array('in',array('0','1'));
        }
        $payment_where['status'] = 1;
        //预售和抢购暂不支持货到付款
        $orderGoodsPromType = M('order_goods')->where(['order_id'=>$order['order_id']])->getField('prom_type',true);
        if($order['order_prom_type'] == 4 || in_array(1,$orderGoodsPromType)){
            $payment_where['code'] = array('neq','cod');
        }
        $paymentList = M('Plugin')->where($payment_where)->select();
        $paymentList = convert_arr_key($paymentList, 'code');

        foreach($paymentList as $key => $val)
        {
            $val['config_value'] = unserialize($val['config_value']);
            if($val['config_value']['is_bank'] == 2)
            {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
            //判断当前浏览器显示支付方式
            if(($key == 'weixin' && !is_weixin()) || ($key == 'alipayMobile' && is_weixin())){
                unset($paymentList[$key]);
            }
        }

        $bank_img = include APP_PATH.'home/bank.php'; // 银行对应图片
        $payment = M('Plugin')->where("`type`='payment' and status = 1")->select();
        $this->assign('paymentList',$paymentList);
        $this->assign('bank_img',$bank_img);
        $this->assign('order',$order);
        $this->assign('bankCodeList',$bankCodeList);
        $this->assign('pay_date',date('Y-m-d', strtotime("+1 day")));
        return $this->fetch();
    }

    
    /**
     * ajax 获取用户收货地址 用于购物车确认订单页面
     */
    public function ajaxAddress(){
        $regionList = get_region_list();
        $address_list = M('UserAddress')->where("user_id", $this->user_id)->select();
        $c = M('UserAddress')->where("user_id = {$this->user_id} and is_default = 1")->count(); // 看看有没默认收货地址
        if((count($address_list) > 0) && ($c == 0)) // 如果没有设置默认收货地址, 则第一条设置为默认收货地址
            $address_list[0]['is_default'] = 1;

        $this->assign('regionList', $regionList);
        $this->assign('address_list', $address_list);
        return $this->fetch('ajax_address');
    }
	
	 /**
     *  获取发票信息
     * @date2017/10/19 14:45
     */
    public function invoice(){

        $map = [];
        $map['user_id']=  $this->user_id;
        
        $field=[          
            'invoice_title',
            'taxpayer',
            'invoice_desc',	
        ];
        
        $info = M('user_extend')->field($field)->where($map)->find();
        if(empty($info)){
            $result=['status' => -1, 'msg' => 'N', 'result' =>''];
        }else{
            $result=['status' => 1, 'msg' => 'Y', 'result' => $info];
        }
        $this->ajaxReturn($result);            
    }
	
	
     /**
     *  保存发票信息
     * @date2017/10/19 14:45
     */
    public function save_invoice(){     
        
        //A.1获取发票信息
        $invoice_title = trim(I("invoice_title"));
        $taxpayer      = trim(I("taxpayer"));
        $invoice_desc  = trim(I("invoice_desc"));
		$realname = trim(I("realname/s",''));
        $user_id = I('uid/d',0);
		$this->user_id = $user_id;
        //B.1校验用户是否有历史发票记录
        $map            = [];
        $map['user_id'] =  $this->user_id;
        $info           = M('user_extend')->where($map)->find();
        
       //B.2发票信息
        $data=[];  
        $data['invoice_title'] = $invoice_title;
        $data['taxpayer']      = $taxpayer;  
        $data['invoice_desc']  = $invoice_desc;     
        $data['realname']  = $realname; 
        //B.3发票抬头
        if($invoice_title=="个人"){
            $data['invoice_title'] ="个人";
            $data['taxpayer']      = "";
        }                              
        
        
        //是否存贮过发票信息
        if(empty($info)){   
            $data['user_id'] = $this->user_id;
            (M('user_extend')->add($data))?
            $status=1:$status=-1;                
         }else{
            (M('user_extend')->where($map)->save($data))?
            $status=1:$status=-1;                
        }            

		$this->returnMsg($status);
    }
}
